package com.ctsi.oauth.config;

import com.ctsi.auth.integration.UserLoginRecordFilter;
import com.ctsi.framework.security.core.authorize.AuthorizeConfigManager;
import com.ctsi.oauth.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


@Configuration
@EnableWebSecurity(debug = true)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   private static final Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);

    private SecurityProperties securityProperties;

    @Autowired
    public WebSecurityConfig(SecurityProperties securityProperties,UserDetailsService userDetailsServiceImpl) {
        this.securityProperties = securityProperties;
        this.userDetailsServiceImpl = userDetailsServiceImpl;
    }


   private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private UserLoginRecordFilter userLoginRecordFilter;

    /**
     * 记住我 remember me
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "cloud.security.browser",name = "remember-me",matchIfMissing = false)
    public PersistentTokenRepository persistentTokenRepository() {
        InMemoryTokenRepositoryImpl tokenRepository = new InMemoryTokenRepositoryImpl();
        return tokenRepository;
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

//    public IntegrationAuthenticationPwdFilter integrationAuthenticationPwdFilter() throws Exception {
//        IntegrationAuthenticationPwdFilter integrationAuthenticationPwdFilter = new IntegrationAuthenticationPwdFilter();
//        integrationAuthenticationPwdFilter.setAuthenticationManager(authenticationManagerBean());
//        return integrationAuthenticationPwdFilter;
//    }

    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().anonymous().disable().httpBasic();
        http.formLogin().disable();
       // http.authorizeRequests().antMatchers("**/oauth/**").permitAll()
       // http.addFilterAt(integrationAuthenticationPwdFilter(), UsernamePasswordAuthenticationFilter.class);
        //http.addFilterBefore(userLoginRecordFilter, ChannelProcessingFilter.class);
        this.authorizeConfigManager.config(http.authorizeRequests());
        //任何请求,登录后可以访问
        http.authorizeRequests().anyRequest().permitAll();
        // 记住我功能
        if (securityProperties.getBrowser().isRememberMe()) {
            http.rememberMe().tokenRepository(persistentTokenRepository())
                    .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
            .userDetailsService(userDetailsServiceImpl);
        }
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsServiceImpl)
                .passwordEncoder(passwordEncoder).withObjectPostProcessor(new ObjectPostProcessor<DaoAuthenticationProvider>() {

            @Override
            public <O extends DaoAuthenticationProvider> O postProcess(O object) {
                 object.setForcePrincipalAsString(false);
                return object;
            }
        });
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

}
